<template>
  <el-scrollbar height="calc(100vh - 120px)">
    <div class="personal-data">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item @click="goBack">返回</el-breadcrumb-item>
        <el-breadcrumb-item>个人信息</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="info-data">
        <div class="title"><span></span>基本信息</div>
        <div class="basic-info">
          <el-form
            ref="userFormRef"
            :model="userForm"
            label-position="top"
            :rules="rules"
            label-width="120px"
            class="demo-userForm"
          >
            <el-form-item label="企业账号">
              <el-input v-model.trim="userForm.accountId" placeholder="请输入" disabled> </el-input>
            </el-form-item>
            <el-form-item label="工号">
              <el-input v-model.trim="userForm.agentNumber" placeholder="请输入" disabled> </el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="agentName">
              <el-input v-model.trim="userForm.agentName" placeholder="请输入"> </el-input>
            </el-form-item>
            <el-form-item label="手机号码" prop="mobile">
              <el-input v-model.trim="userForm.mobile" placeholder="请输入"> </el-input>
            </el-form-item>
          </el-form>
          <div class="info-logo">
            <div class="user-img">
              <img class="agent-img" v-if="userImage" :src="userImage" alt="" />
              <div class="default-img" v-else>{{ userText }}</div>
              <upload accept="image/*" :show-file-list="false" :on-success="onUpload" class="upload-box">
                <template #trigger>
                  <div>
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <el-button size="mini" class="img-btn"
                      ><i class="MC_iconfont MC_icon-shangchuan-shangchuan"></i>上传头像</el-button
                    >
                  </div>
                </template>
              </upload>
            </div>
          </div>
        </div>
        <div class="psd-info">
          <div class="title"><span></span>密码更改</div>
          <div class="possword">
            <div class="pass-label">密码</div>
            <el-button @click="update" size="mini" :icon="Lock">更改密码</el-button>
          </div>
        </div>
      </div>
      <div class="footer">
        <el-button type="default" class="footer-cancel" @click="infoCancel">取消</el-button>
        <el-button type="primary" class="footer-save" @click="infoSave">保存</el-button>
      </div>
      <move-dialog
        :visible="dialogFormVisibleA"
        :title="'更改密码'"
        :width="480"
        :beforeClose="beforeClose"
        class="psd-form"
      >
        <el-form
          :model="passwordForm"
          label-width="150px"
          label-position="top"
          :rules="passRules"
          ref="ruleForm"
          class="editPsd-form"
        >
          <el-form-item label="旧密码:" prop="oldPassword" style="height: 70px">
            <el-input
              v-model.trim="passwordForm.oldPassword"
              :type="passwordControl.oldPass.passwordType"
              placeholder="请输入原密码"
              auto-complete="off"
            >
              <template #suffix>
                <i
                  class="MC_iconfont MC_icon-yulan-yincang pass-icon"
                  v-show="passwordControl.oldPass.passwordType === 'password'"
                  @click="passwordShowFun('text', 'oldPass')"
                ></i>
                <i
                  class="MC_iconfont MC_icon-yulan-yulan pass-icon"
                  v-show="passwordControl.oldPass.passwordType === 'text'"
                  @click="passwordShowFun('password', 'oldPass')"
                ></i>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="新密码:" prop="newPassword" style="height: 70px">
            <el-input
              v-model.trim="passwordForm.newPassword"
              :type="passwordControl.currentPass.passwordType"
              placeholder="可由字母、数字、特殊符号组成，长度为8～18字"
              auto-complete="off"
            >
              <template #suffix>
                <i
                  slot="suffix"
                  class="MC_iconfont MC_icon-yulan-yincang pass-icon"
                  v-show="passwordControl.currentPass.passwordType === 'password'"
                  @click="passwordShowFun('text', 'currentPass')"
                ></i>
                <i
                  slot="suffix"
                  class="MC_iconfont MC_icon-yulan-yulan pass-icon"
                  v-show="passwordControl.currentPass.passwordType === 'text'"
                  @click="passwordShowFun('password', 'currentPass')"
                ></i>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="确认新密码:" prop="confirmNewPasswords" style="height: 70px">
            <el-input
              v-model.trim="passwordForm.confirmNewPasswords"
              :type="passwordControl.newPass.passwordType"
              placeholder="请再次确认新密码"
              auto-complete="off"
            >
              <template #suffix>
                <i
                  slot="suffix"
                  class="MC_iconfont MC_icon-yulan-yincang pass-icon"
                  v-show="passwordControl.newPass.passwordType === 'password'"
                  @click="passwordShowFun('text', 'newPass')"
                ></i>
                <i
                  slot="suffix"
                  class="MC_iconfont MC_icon-yulan-yulan pass-icon"
                  v-show="passwordControl.newPass.passwordType === 'text'"
                  @click="passwordShowFun('password', 'newPass')"
                ></i>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button type="default" @click="passCancel">取消</el-button>
          <el-button type="primary" @click="passSave">保存</el-button>
        </template>
      </move-dialog>
    </div>
  </el-scrollbar>
</template>

<script lang="ts">
import { defineComponent, getCurrentInstance, reactive, toRefs, onMounted } from 'vue'
import { Lock, Download } from '@element-plus/icons-vue'
import moveDialog from '@common/components/move-dialog/index.vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { deepClone } from '@/common/utils/common'
import md5 from 'js-md5'
import { editPassword, getPersonInfo, updatePersonInfo } from '@app/base/apis/person-info'
import Upload from '@/common/components/upload/index.vue'
import { ExtendFile } from '@/common/utils/upload'
import { userModule } from '@/common/store/modules/user'
import { regexPass } from '@/common/utils/validate'
import { isNumber2 } from '@/common/utils/validate'
interface State {
  userForm: any
  passwordForm: any
  passwordControl: any
  value1: boolean
  dialogFormVisibleA: boolean
  fileName: string
  userImage: any
  userText: any
  title: string
  rules: any
  passRules: any
}
export default defineComponent({
  name: 'AdminMain',
  components: {
    moveDialog,
    Upload
  },
  // ----------------生命周期-----------------------
  setup() {
    const ROUTER = useRouter()
    const instance: any = getCurrentInstance()
    const USERMODULE = userModule()
    const validateNumber = (rule: any, value: any, callback: any) => {
      if (value !== '') {
        if (!isNumber2(value)) {
          callback(new Error('请输入正确的数字'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    const getFormPass = () => {
      // validator中直接取form值只能取到初始化的"", 所以需要通过方法转换下
      return state.passwordForm.newPassword
    }
    const validatePass = (rule: any, value: any, callback: any) => {
      // 输入的新密码校验
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (!regexPass(value, getFormPass())) {
        callback(
          new Error(
            '密码必须8~18位，并包含数字，小写字母，大写字母，特殊字符中的至少3种，特殊字符不能是%、&、+、\'、\\"、<、>、='
          )
        )
      } else {
        callback()
      }
    }
    const validatePass2 = (rule: any, value: any, callback: any) => {
      // 再次确认密码的校验
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (!regexPass(value, getFormPass())) {
        callback(
          new Error(
            '密码必须大于等于8位，并包含数字，小写字母，大写字母，特殊字符中的至少3种，特殊字符不能是%、&、+、\'、\\"、<、>、='
          )
        )
      } else if (value !== getFormPass()) {
        callback(new Error('密码与新密码不一致'))
      } else {
        callback()
      }
    }
    const state: State = reactive({
      userForm: {
        _id: '',
        agentName: '',
        agentNumber: '',
        mobile: '',
        accountId: '北京容联七陌科技有限公司',
        icon: '',
        email: ''
      },
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmNewPasswords: ''
      },
      value1: true,
      fileName: '',
      userImage: '',
      userText: '',
      dialogFormVisibleA: false,
      title: '更改密码',
      // 表单校验
      rules: {
        agentName: [{ required: true, message: '必填', trigger: 'blur' }],
        mobile: [{ required: false, validator: validateNumber, trigger: 'blur' }]
      },
      passRules: {
        oldPassword: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        newPassword: [{ required: true, validator: validatePass, trigger: 'blur' }],
        confirmNewPasswords: [{ required: true, validator: validatePass2, trigger: 'blur' }]
      },
      passwordControl: {
        // 密码表单的小眼睛控制
        oldPass: { passwordType: 'password' },
        currentPass: { passwordType: 'password' },
        newPass: { passwordType: 'password' }
      }
    })
    // 更改密码
    function update() {
      state.dialogFormVisibleA = true
    }
    // 更改密码取消
    function passCancel() {
      instance?.refs.ruleForm.resetFields()
      state.dialogFormVisibleA = false
    }
    // 关闭更改密码弹窗
    function beforeClose() {
      instance?.refs.ruleForm.resetFields()
      state.dialogFormVisibleA = false
    }
    // 更改密码保存
    function passSave() {
      instance?.refs.ruleForm.validate((valid: boolean) => {
        if (valid) {
          const cloneFrom = deepClone(state.passwordForm)
          const oldPassword = md5(cloneFrom.oldPassword) || ''
          const newPassword = md5(cloneFrom.newPassword) || ''
          const actionData = { oldPassword, newPassword }
          editPassword(actionData).then((res) => {
            if (res && res.success) {
              ElMessage.success('修改密码成功')
              instance?.refs.ruleForm.resetFields()
              state.dialogFormVisibleA = false
            }
          })
        } else {
          return false
        }
      })
    }
    // 个人信息保存
    const infoSave = () => {
      instance?.refs.userFormRef.validate((valid: boolean) => {
        if (valid) {
          const sendData = {
            _id: state.userForm._id,
            agentName: state.userForm.agentName,
            icon: state.userForm.icon,
            mobile: state.userForm.mobile
          }
          updatePersonInfo(sendData).then((res) => {
            if (res && res.success) {
              userModule().setUserInfo(res.data)
              ElMessage.success('保存成功')
              state.userText = res.data.pinyin ? res.data.pinyin.substr(0, 1).toLocaleUpperCase() : ''
            }
          })
        }
      })
    }
    // 个人信息取消
    const infoCancel = () => {
      ROUTER.back()
    }
    const goBack = () => {
      ROUTER.back()
    }

    // 获取个人信息
    const getInfoData = () => {
      getPersonInfo().then((res) => {
        state.userForm = res.data || {
          _id: '',
          agentName: '',
          agentNumber: '',
          mobile: '',
          accountId: '北京容联七陌科技有限公司',
          icon: ''
        }
        state.userImage = state.userForm.icon ? state.userForm.icon : ''
        state.userText = USERMODULE.agent.pinyin ? USERMODULE.agent.pinyin.substr(0, 1).toLocaleUpperCase() : ''
      })
    }

    const onUpload = (file: ExtendFile) => {
      state.userForm.icon = file.url || ''
      console.log(file, 'file')
      state.userImage = file.url || ''
    }

    const passwordShowFun = (type: string, pass: any) => {
      // 密码是否可见切换事件
      state.passwordControl[pass].passwordType = type
    }

    onMounted(() => {
      getInfoData()
    })

    return {
      ...toRefs(state),
      Lock,
      Download,
      update,
      passCancel,
      passSave,
      infoCancel,
      infoSave,
      goBack,
      onUpload,
      beforeClose,
      passwordShowFun
    }
  }
})
</script>
<style lang="stylus" scoped>
.personal-data
  display: flex;
  flex-direction: column;
  padding: 24px 40px;
  gap: 16px;
  width: 100%;
  // max-height: 100%;
  background: #FFFFFF;
  flex: none;
  order: 0;
  align-self: stretch;
  box-sizing border-box
  flex-grow: 1;
  // overflow-y: auto;
  .el-breadcrumb
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: 0px
    gap: 8px;
    width: 100%;
    height 20px
    background: #FFFFFF;
    flex: none;
    order: 0;
    align-self: stretch;
    flex-grow: 0;
    box-sizing border-box
    .el-breadcrumb__item
      cursor pointer
  .info-data
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    padding: 0px;
    width: 100%;
    flex: none;
    order: 1;
    flex-grow: 0;
    .title
      display: flex;
      flex-direction: row;
      align-items: center;
      padding: 8px 0px 16px;
      gap: 8px;
      width: 77px;
      height: 46px;
      flex: none;
      order: 0;
      flex-grow: 0;
      font-weight: 500;
      font-size: 16px;
      line-height: 22px;
      letter-spacing: 0.001em;
      color: rgba(0, 0, 0, 0.88);
      box-sizing border-box
      span
        width: 4px;
        height: 16px;
        background: var(--mc-main-color);
        border-radius: 2px;
        flex: none;
        order: 0;
        flex-grow: 0;
    .basic-info
      display: flex;
      flex-direction: row;
      align-items: flex-start;
      padding: 0px;
      gap: 40px;
      width: 553px;
      height: 352px;
      flex: none;
      order: 1;
      flex-grow: 0;
      .demo-userForm
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        padding: 0px;
        width: 400px;
        height: 352px;
        flex: none;
        order: 0;
        flex-grow: 0;
        .el-form-item
          width 100%
          height 88px
        .el-form-item__label
          color: rgba(0, 0, 0, 0.6)
          font-size 14px
        .agent-text
          display: inline-block;
          position: absolute;
          height 20px
          width 100%
          left: 94px;
          top 55px
          font-size: 12px
          color: rgba(0, 0, 0, 0.6);
          margin 0
      .info-logo
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 0px;
        gap: 16px;
        width: 113px;
        height: 132px;
        flex: none;
        order: 1;
        flex-grow: 0;
        .user-img
          position relative
          height 86px
          width 100%
          display: flex;
          flex-direction: column;
          align-items: center;
          .default-img
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
            padding: 0px;
            gap: 10px;
            width: 80px;
            height: 80px;
            background: var(--mc-main-color);
            border-radius: 56px;
            flex: none;
            order: 0;
            flex-grow: 0;
            color #fff
            font-size: 24px;
            line-height: 32px;
          .agent-img
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
            padding: 0px;
            gap: 10px;
            width: 80px;
            height: 80px;
            border-radius: 56px;
            flex: none;
            order: 0;
            flex-grow: 0;
            color #fff
            font-size: 24px;
            line-height: 32px;
          .img-btn
            i
              margin-right 8.5px
    .psd-info
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      padding: 0px;
      width: 113px;
      height: 134px;
      flex: none;
      order: 2;
      flex-grow: 0;
      .possword
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        padding: 12px 0px;
        gap: 8px;
        width: 137px;
        height: 64px;
        flex: none;
        flex-grow: 0;
        .pass-label
          color: rgba(0, 0, 0, 0.6)
          font-size 14px
  .footer
      position: fixed
      right 0
      bottom: 0
      height 50px
      width 100%
      height: 60px;
      display: flex;
      flex-direction: row;
      justify-content: flex-end;
      align-items: center;
      padding: 14px 24px;
      background: #FFFFFF;
      box-shadow: 0px -1px 0px rgba(0, 0, 0, 0.05);
      flex: none;
      order: 1;
      align-self: stretch;
      flex-grow: 0;
      box-sizing border-box
      .footer-save
        display: flex;
        flex-direction: row;
        align-items: center;
        padding: 8px 16px;
        gap: 8px;
        width: 61px;
        height: 36px;
        border-radius: 4px;
        flex: none;
        order: 1;
        flex-grow: 0;
      .footer-cancel
        display: flex;
        flex-direction: row;
        align-items: center;
        padding: 8px;
        gap: 8px;
        width: 45px;
        height: 28x;
        border-radius: 4px;
        flex: none;
        order: 0;
        flex-grow: 0;
        border none
  .pass-icon
    padding-right 6px
</style>
